﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using CADs;
using ModeloGaleriaNET;
using AvalonDock;
using System.Data.Objects.DataClasses;
using System.Data.Objects;
using SeguridadGaleria;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para ucClientes.xaml
    /// </summary>
    public partial class ucClientes : UserControl
    {
        private string[] permisos = new string[] { TiposRoles.CREAR_CLIENTE, TiposRoles.MODIFICAR_DATOS_CLIENTE,
            TiposRoles.ELIMINAR_CLIENTE, TiposRoles.VISUALIZAR_CLIENTE};
        private readonly string title = "Gestión de clientes";
        private readonly int pageSize = int.Parse(CADs.Properties.Resources.PageSize);
        private bool loaded;
        private int numClientes;
        private int pagenum;
        private BackgroundWorker worker, workerPermisos;
        private List<Cliente> clientes;
        private ClienteCAD clienteCAD;
        private int? usuarioAlta;
        private Dictionary<string, bool> permisosDatos;
        string usuario;

        public ucClientes()
        {
            InitializeComponent();
            #region Definición del BackgroundWorker
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            workerPermisos = new BackgroundWorker();
            workerPermisos.DoWork += workerPermisos_DoWork;
            workerPermisos.RunWorkerCompleted += workerPermisos_RunWorkerCompleted;
            #endregion
            usuarioAlta = null;
            loaded = false; 
            dgClientes.Columns.Add(FindResource("resColumnaObra") as DataGridTemplateColumn);
        }

        public ucClientes(int uAlta)
        {
            InitializeComponent();
            usuarioAlta = uAlta;
            #region Definición del BackgroundWorker
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            workerPermisos = new BackgroundWorker();
            workerPermisos.DoWork += workerPermisos_DoWork;
            workerPermisos.RunWorkerCompleted += workerPermisos_RunWorkerCompleted;
            #endregion
            dgClientes.Columns.Add(FindResource("resColumnaObra") as DataGridTemplateColumn);
        }
       
        public string Title
        {
            get { return title; }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                clientes = clienteCAD.GetClientesPaginated(pagenum);
                numClientes = clienteCAD.GetClientesCount();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btAnterior_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                pagenum--;
                worker.RunWorkerAsync();
            }
        }

        private void btSiguiente_Click(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                pagenum++;
                worker.RunWorkerAsync();
            }
        }

        private void btSiguiente_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtSiguiente != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Right_24.GetHbitmap() : Properties.Resources.RightBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtSiguiente.Source = bs;
            }
        }

        private void btAnterior_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            IntPtr b;
            BitmapSource bs;

            if (imgBtAnterior != null)
            {
                b = Convert.ToBoolean(e.NewValue) ? Properties.Resources.Left_24.GetHbitmap() : Properties.Resources.LeftBW_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtAnterior.Source = bs;
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
             _busyIndicator.IsBusy = false;
            dgClientes.ItemsSource = clientes;
            tbPaginacion.Visibility = Visibility.Visible;
            UpdatePaginationControls();
        }

        private void workerPermisos_DoWork(object sender, DoWorkEventArgs e)
        {
            bool? value;
            DependencyObject padre;

            padre = this.Parent;
            if (padre is AvalonDock.DocumentContent)
            {
                padre = ((AvalonDock.DocumentContent)padre).Manager;
                if (padre is AvalonDock.DockingManager)
                {
                    padre = ((AvalonDock.DockingManager)padre).Parent;
                    if (padre is Grid)
                    {
                        padre = ((Grid)padre).Parent;

                        if (padre is UserWindow)
                            usuario = ((UserWindow)padre).Usuario.PseudonimoLocal;
                        else
                            throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                    }
                    else
                        throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                }
                else
                    throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
            }
            else
                throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");

            permisosDatos = new Dictionary<string, bool>();
            foreach (string s in permisos)
            {
                value = ManejadorRoles.Instance.CanUse(s, usuario);
                if (value != null)
                    permisosDatos.Add(s, value.Value);
            }
        }

        private void workerPermisos_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            bool value, value2;
            IntPtr b;
            BitmapSource bs;

            if (permisosDatos == null || permisosDatos.Count != permisos.Length)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("No se han podido obtener los permisos", "Error",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                dgClientes.MouseDoubleClick -= dgClientes_MouseDoubleClick;
                btNuevo.IsEnabled = false;
                b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                  System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                this.imgBtNuevo.Source = bs;
                
            }
            else
            {
                permisosDatos.TryGetValue(TiposRoles.VISUALIZAR_CLIENTE, out value);
                if (value == false)
                {
                    dgClientes.MouseDoubleClick -= dgClientes_MouseDoubleClick;
                    btNuevo.IsEnabled = false;
                    b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                    bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                      System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                    this.imgBtNuevo.Source = bs;
                }
                else
                {
                    permisosDatos.TryGetValue(TiposRoles.MODIFICAR_DATOS_CLIENTE, out value);
                    permisosDatos.TryGetValue(TiposRoles.ELIMINAR_CLIENTE, out value2);

                    if (value2 == false && value == false)
                        dgClientes.MouseDoubleClick -= dgClientes_MouseDoubleClick;

                    permisosDatos.TryGetValue(TiposRoles.CREAR_CLIENTE, out value);
                    if (value == false)
                    {
                        b = Properties.Resources.Agregar_gris_24.GetHbitmap();
                        bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                          System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                        this.imgBtNuevo.Source = bs;
                        btNuevo.IsEnabled = false;
                    }
                    else
                    {
                        btNuevo.IsEnabled = true;
                        b = Properties.Resources.Agregar_24.GetHbitmap();
                        bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b, IntPtr.Zero, Int32Rect.Empty,
                          System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                        this.imgBtNuevo.Source = bs;
                    }
                }
            }
        }

        private void UpdatePaginationControls()
        {
            String iniString = "0";
            String deString = "";

            if (numClientes > 0)
                iniString = (pagenum * pageSize + 1).ToString();

            btAnterior.IsEnabled = pagenum == 0 ? false : true;

            if (pagenum + 1 >= numClientes / (float)pageSize)
            {
                btSiguiente.IsEnabled = false;
                deString = numClientes.ToString();
            }
            else
            {
                btSiguiente.IsEnabled = true;
                deString = ((pagenum + 1) * pageSize).ToString();
            }

            lbPagina.Content = iniString + " - " + deString + " de " + numClientes;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            List<ClienteFilter> filtros;
            ClienteFilter filtro;

            if (!loaded)
            {
                if (!worker.IsBusy)
                {
                    _busyIndicator.IsBusy = true;
                    clienteCAD = new ClienteCAD();

                    if (usuarioAlta == null)
                        clienteCAD.SetQueryFilters(null);
                    else
                    {
                        filtro = new ClienteFilter("it.usuarioAlta = @inputAlta");
                        filtro.Parameters.Add(new ObjectParameter("inputAlta", usuarioAlta));
                        filtros = new List<ClienteFilter>();
                        filtros.Add(filtro);
                        clienteCAD.SetQueryFilters(filtros);
                    }
                    if (workerPermisos.IsBusy == false)
                        workerPermisos.RunWorkerAsync();
                    System.Threading.Thread.Sleep(1000);

                    numClientes = -1;
                    pagenum = 0;
                    worker.RunWorkerAsync();

                    
                }
                loaded = true;
            }
        }

        private void dgClientes_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataGrid grid;
            DataGridRow dgr;
            DocumentContent doc;
            
            if (sender != null)
            {
                grid = sender as DataGrid;
                if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
                {
                    dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
                    if (dgr.Item is EntityObject)
                    {
                        doc = FindDocumentContent(typeof(ucClientData));
                        if (doc == null)
                            ShowPageInParentDock<ucClientData>(((EntityObject)dgr.Item));
                        else
                            MessageBox.Show("Ya hay abierta una ventana de creación o edición de clientes. Ciérrela antes de abrir otra.",
                                "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }

        private void btNuevo_Click(object sender, RoutedEventArgs e)
        {
            DocumentContent doc = FindDocumentContent(typeof(ucClientData));

            if (doc == null)
                ShowPageInParentDock<ucClientData>();
            else
                MessageBox.Show("Ya hay abierta una ventana de creación o edición de clientes. Ciérrela antes de abrir otra.",
                    "Error", MessageBoxButton.OK, MessageBoxImage.Error);    
        }

        private DocumentContent FindDocumentContent(Type t)
        {
            AvalonDock.DockingManager manager;

            manager = ((AvalonDock.DocumentContent)this.Parent).Manager;
            // Buscamos si hay abierta una instancia del documento a abrir
            foreach (AvalonDock.DocumentContent doc in manager.Documents)
            {
                if (doc.Content.GetType() == t)
                    return doc;
            }
            return null;
        }

        public void ActualizarDataGrid()
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                dgClientes.ItemsSource = null;
                numClientes = -1;
                worker.RunWorkerAsync();
            }
        }

        private void ShowPageInParentDock<T>(EntityObject obj = null) where T : UserControl
        {
            ucClientData control;

            control = obj != null ? new ucClientData((Cliente)obj, usuario) : new ucClientData(usuario);
            control.ClienteCAD = clienteCAD;
            OpenNewDocument(control);
        }

        private void btLimpiar_Click(object sender, RoutedEventArgs e)
        {
            _busyIndicator.IsBusy = true;
            clienteCAD.SetQueryFilters(null);
            numClientes = -1;
            pagenum = 0;
            worker.RunWorkerAsync();
        }

        private void btBuscar_Click(object sender, RoutedEventArgs e)
        {
            ClienteFilterWindow busqueda;

            busqueda = new ClienteFilterWindow();
            busqueda.ShowDialog();

            if (busqueda.Success) // Realizar búsqueda
            {
                if (!worker.IsBusy)
                {
                    _busyIndicator.IsBusy = true;
                    clienteCAD.SetQueryFilters(busqueda.Filters);
                    dgClientes.ItemsSource = null;
                    dgClientes.Items.Clear();
                    numClientes = -1;
                    pagenum = 0;
                    worker.RunWorkerAsync();
                }
            }
        }

        private void OpenNewDocument(UserControl c)
        {
            DependencyObject padre;

            try
            {
                padre = this.Parent;
                if (padre is AvalonDock.DocumentContent)
                {
                    padre = ((AvalonDock.DocumentContent)padre).Manager;
                    if (padre is AvalonDock.DockingManager)
                    {
                        padre = ((AvalonDock.DockingManager)padre).Parent;
                        if (padre is Grid)
                        {
                            padre = ((Grid)padre).Parent;

                            if (padre is UserWindow)
                            {
                                if (c is ucClientData)
                                    ((UserWindow)padre).ShowPage<ucClientData>((ucClientData)c);
                                else if (c is ucObras)
                                    ((UserWindow)padre).ShowPage<ucObras>((ucObras)c);
                            }
                            else
                                throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                        }
                        else
                            throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                    }
                    else
                        throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
                }
                else
                    throw new ErrorOpeningNewDocumentException("No se puede abrir la nueva ventana");
            }
            catch (ErrorOpeningNewDocumentException ex)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        private void btObras_Click(object sender, RoutedEventArgs e)
        {
            DocumentContent doc;
            ucObras control;
            DataGridRow dgr;

            if (sender != null)
            {
                if (dgClientes.SelectedItems != null && dgClientes.SelectedItems.Count == 1)
                {
                    doc = FindDocumentContent(typeof(ucObras));
                    if (doc != null)
                        Xceed.Wpf.Toolkit.MessageBox.Show("Hay abierta una ventana de listado de obras.\nCiérrela antes de abrir otra",
                            "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    {
                        dgr = dgClientes.ItemContainerGenerator.ContainerFromItem(dgClientes.SelectedItem) as DataGridRow;
                        control = new ucObras((Cliente)dgr.Item);
                        OpenNewDocument(control);

                    }
                }
            }
        }
    }
}
